package megrez.job.xxljob.jobhandler;

import java.io.IOException;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;

import megrez.job.common.ShellHelper;

/**
 * 命令行任务
 *  
 * @author Lucky Yang
 * @since 2.6.9
 */
@Component
public class Command {
    @XxlJob("command")
    public void execute() throws InterruptedException  {
        String command = XxlJobHelper.getJobParam();
        if (!StringUtils.hasText(command)) {
            XxlJobHelper.log("param["+ command +"] invalid.");

            XxlJobHelper.handleFail();
            return;
        }

        int exitValue = -1 ;
        try {
            exitValue = ShellHelper.execute(List.of(command), XxlJobHelper::log);
        } catch (IOException e) {
            XxlJobHelper.log(e);
        }

        if (exitValue == 0) {
            // default success
            XxlJobHelper.log("command exit is successful");
        } else {
            XxlJobHelper.handleFail("command exit value("+exitValue+") is failed");
        }

    }
}
